package zhoufu.sz.sanxiao_check.utils;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.PorterDuffXfermode;
import android.util.Log;
import android.widget.ImageView;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;

import static android.graphics.Bitmap.Config.ARGB_8888;
import static android.graphics.Color.WHITE;
import static android.graphics.PorterDuff.Mode.DST_IN;

public class ImageUtils
{

    private static final String TAG = "ImageUtils";

    /**
     * Get a bitmap from the image path
     *
     * @return bitmap or null if read fails
     */
    public static Bitmap getBitmap(final String imagePath)
    {
        return getBitmap(imagePath, 1);
    }

    /**
     * Get a bitmap from the image path
     *
     * @return bitmap or null if read fails
     */
    public static Bitmap getBitmap(final String imagePath, int sampleSize)
    {
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inDither = false;
        options.inSampleSize = sampleSize;
        options.inPreferredConfig = Bitmap.Config.RGB_565;

        RandomAccessFile file = null;
        try
        {
            file = new RandomAccessFile(imagePath, "r");
            return BitmapFactory.decodeFileDescriptor(file.getFD(), null, options);
        } catch (IOException e)
        {
            Log.d(TAG, e.getMessage(), e);
            return null;
        } finally
        {
            if ( file != null )
            {
                try
                {
                    file.close();
                } catch (IOException e)
                {
                    Log.d(TAG, e.getMessage(), e);
                }
            }
        }
    }

    /**
     * Get a bitmap from the image path
     *
     * @return bitmap or null if read fails
     */
    public static Bitmap getBitmap(final int id)
    {
        return BitmapFactory.decodeResource(UIUtils.getResources(), id);
    }

    /**
     * Get a bitmap from the image
     *
     * @return bitmap or null if read fails
     */
    public static Bitmap getBitmap(final byte[] image, int sampleSize)
    {
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inDither = false;
        options.inSampleSize = sampleSize;
        return BitmapFactory.decodeByteArray(image, 0, image.length, options);
    }

    /**
     * Get scale for image of size and max height/width
     *
     * @return scale
     */
    public static int getScale(Point size, int width, int height)
    {
        if ( size.x > width || size.y > height )
        {
            return Math.max(Math.round((float) size.y / (float) height),
                    Math.round((float) size.x / (float) width));
        } else
        {
            return 1;
        }
    }

    /**
     * Get size of image
     *
     * @return size
     */
    public static Point getSize(final String imagePath)
    {
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;

        RandomAccessFile file = null;
        try
        {
            file = new RandomAccessFile(imagePath, "r");
            BitmapFactory.decodeFileDescriptor(file.getFD(), null, options);
            return new Point(options.outWidth, options.outHeight);
        } catch (IOException e)
        {
            Log.d(TAG, e.getMessage(), e);
            return null;
        } finally
        {
            if ( file != null )
            {
                try
                {
                    file.close();
                } catch (IOException e)
                {
                    Log.d(TAG, e.getMessage(), e);
                }
            }
        }
    }

    /**
     * Get size of image
     *
     * @return size
     */
    public static Point getSize(final byte[] image)
    {
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeByteArray(image, 0, image.length, options);
        return new Point(options.outWidth, options.outHeight);
    }

    /**
     * Get bitmap with maximum height or width
     *
     * @return image
     */
    public static Bitmap getBitmap(final String imagePath, int width, int height)
    {
        Point size = getSize(imagePath);
        return getBitmap(imagePath, getScale(size, width, height));
    }

    /**
     * Get bitmap with maximum height or width
     *
     * @return image
     */
    public static Bitmap getBitmap(final byte[] image, int width, int height)
    {
        Point size = getSize(image);
        return getBitmap(image, getScale(size, width, height));
    }

    /**
     * Get bitmap with maximum height or width
     *
     * @return image
     */
    public static Bitmap getBitmap(final File image, int width, int height)
    {
        return getBitmap(image.getAbsolutePath(), width, height);
    }

    /**
     * Get a bitmap from the image file
     *
     * @return bitmap or null if read fails
     */
    public static Bitmap getBitmap(final File image)
    {
        return getBitmap(image.getAbsolutePath());
    }

    /**
     * Load a {@link Bitmap} from the given path and set it on the given
     * {@link ImageView}
     */
    public static void setImage(final String imagePath, final ImageView view)
    {
        setImage(new File(imagePath), view);
    }

    /**
     * Load a {@link Bitmap} from the given {@link File} and set it on the given
     * {@link ImageView}
     */
    public static void setImage(final File image, final ImageView view)
    {
        Bitmap bitmap = getBitmap(image);
        if ( bitmap != null )
        {
            view.setImageBitmap(bitmap);
        }
    }

    /**
     * Round the corners of a {@link Bitmap}
     *
     * @return rounded corner bitmap
     */
    public static Bitmap roundCorners(final Bitmap source, final float radius)
    {
        int width  = source.getWidth();
        int height = source.getHeight();

        Paint paint = new Paint();
        paint.setAntiAlias(true);
        paint.setColor(WHITE);

        Bitmap clipped = Bitmap.createBitmap(width, height, ARGB_8888);
        Canvas canvas  = new Canvas(clipped);
        canvas.drawCircle(width / 2, height / 2, width / 2, paint);
        //canvas.drawRoundRect(new RectF(0, 0, width, height), radius, radius, paint);
        paint.setXfermode(new PorterDuffXfermode(DST_IN));

        Bitmap rounded = Bitmap.createBitmap(width, height, ARGB_8888);
        canvas = new Canvas(rounded);
        canvas.drawBitmap(source, 0, 0, null);
        canvas.drawBitmap(clipped, 0, 0, paint);

        source.recycle();
        clipped.recycle();

        return rounded;
    }

    public static void compressImg(String path)
    {
        final Bitmap bitmap = ImageUtils.getBitmap(path, 400, 800);
        String       s      = FileUtils.getCacheDir() + "UpCache/";
        FileUtils.createDirs(s);
        final String upPath = s + "temp" + System.currentTimeMillis() + ".jpg";
        ThreadManager.getLongRunPool().execute(new Runnable()
        {
            @Override public void run()
            {
                if ( runPress(upPath, bitmap) )
                {
//                    EventBus.getDefault().post(upPath);
                    bitmap.recycle();
                }
            }
        });
    }

    public static boolean runPress(String path, Bitmap bitmap)
    {
        boolean compress = false;

        FileOutputStream fos = null;
        try
        {
            fos = new FileOutputStream(path);
            BufferedOutputStream bos = new BufferedOutputStream(fos);
            compress = bitmap.compress(Bitmap.CompressFormat.JPEG, 90, bos);
            bos.flush();
        } catch (IOException e)
        {
            e.printStackTrace();
        } finally
        {
            bitmap.recycle();
            if ( fos != null )
            {
                try
                {
                    fos.close();
                } catch (IOException e)
                {
                    e.printStackTrace();
                }
            }
        }
        return compress;
    }
}